package com.example.discover.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.discover.repository.BookRepository


class BookViewModelFactory: ViewModelProvider.Factory {

    lateinit var repository: BookRepository

    private val viewModelCache:MutableMap<String,ViewModel> = mutableMapOf()

    constructor(){
        if (instance != null){
            throw RuntimeException("Please use BookViewModelFactory.instance")
        }
    }

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {

        if(!viewModelCache.contains(modelClass.canonicalName)){
            Log.i("$this","***********Create model***********${modelClass.canonicalName}")
            when {
                modelClass.isAssignableFrom(BookViewModel::class.java) -> {
                    viewModelCache[modelClass.canonicalName] = BookViewModel(repository)
                }
                modelClass.isAssignableFrom(BookSummaryViewModel::class.java) -> {
                    viewModelCache[modelClass.canonicalName] = BookSummaryViewModel(repository)
                }
                else -> {
                    throw IllegalArgumentException("Unknown ViewModel:${modelClass.canonicalName}")
                }
            }
        }

        return viewModelCache[modelClass.canonicalName!!] as T
    }

    /**
     *
     */
    companion object{
        @Volatile
        var instance : BookViewModelFactory? = null
    }
}